package cn.itcast.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CommonConfig {

    public static final String DIRECT_EXCHANGE = "direct.exchange";
    public static final String DIRECT_ROUTE_KEY = "direct.key";
    public static final String DIRECT_QUEUE = "direct.queue";

    /**
     * 消费失败，转存配置
     */
    public static final String ERROR_EXCHANGE = "error.exchange";
    public static final String ERROR_ROUTE_KEY = "error.key";
    public static final String ERROR_QUEUE = "error.queue";

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(DIRECT_EXCHANGE);
    }

    @Bean
    public Queue directQueue() {
        return new Queue(DIRECT_QUEUE);
    }

    @Bean
    public Binding bindDirectQueue() {
        return BindingBuilder.bind(directQueue()).to(directExchange()).with(DIRECT_ROUTE_KEY);
    }

    @Bean
    public DirectExchange errorExchange() {
        return new DirectExchange(ERROR_EXCHANGE);
    }

    @Bean
    public Queue errorQueue() {
        return new Queue(ERROR_QUEUE);
    }

    @Bean
    public Binding bindErrorQueue() {
        return BindingBuilder.bind(errorQueue()).to(errorExchange()).with(ERROR_ROUTE_KEY);
    }

    /**
     * 声明ttl交换器
     *
     * @return
     */
    @Bean
    public DirectExchange ttlExchange() {
        return new DirectExchange("ttl.exchange");
    }

    /**
     *  声明ttl队列，并设置过期时间，并设置死信交换机和死信路由键
     * @return
     */
    @Bean
    public Queue ttlQueue() {
        return QueueBuilder.durable("ttl.queue")
                .ttl(20000)
                .deadLetterExchange("dl.exchange")
                .deadLetterRoutingKey("dl.key").build();
    }

    /**
     * ttl队列绑定ttl交换机
     * @return
     */
    @Bean
    public Binding bindTtlQueue() {
        return BindingBuilder.bind(ttlQueue()).to(ttlExchange()).with("ttl.key");
    }

    /**
     *  声明惰性队列
     * @return
     */
    @Bean
    public Queue lazyQueue() {
        return QueueBuilder.durable("lazy.queue")
                .lazy() //开启x-queue-mode=lazy
                .build();
    }
}
